package com.recipedb.recipedb.service.impl;

import com.recipedb.recipedb.entity.Ingredient;
import com.recipedb.recipedb.entity.RecipeIngredient;
import com.recipedb.recipedb.entity.RecipeIngredientId;
import com.recipedb.recipedb.repository.IngredientRepository;
import com.recipedb.recipedb.repository.RecipeIngredientRepository;
import com.recipedb.recipedb.service.RecipeIngredientService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
public class RecipeIngredientServiceImpl implements RecipeIngredientService {

    @Autowired
    private RecipeIngredientRepository repository;

    @Autowired
    private com.recipedb.recipedb.repository.IngredientRepository ingredientRepository;

    @Override
    public RecipeIngredient save(RecipeIngredient entity) {
        return repository.save(entity);
    }

    @Override
    public void deleteById(RecipeIngredientId id) {
        repository.deleteById(id);
    }

    @Override
    public Optional<RecipeIngredient> findById(RecipeIngredientId id) {
        return repository.findById(id);
    }

    @Override
    public List<RecipeIngredient> findAll() {
        return repository.findAll();
    }

    // 新增实现
    @Override
    public Map<Ingredient, BigDecimal> findIngredientsByRecipeId(Long recipeId) {
        List<RecipeIngredient> riList = repository.findAll().stream()
                .filter(ri -> ri.getRecipeId().equals(recipeId))
                .collect(Collectors.toList());

        List<Long> ingredientIds = riList.stream()
                .map(RecipeIngredient::getIngredientId)
                .collect(Collectors.toList());

        List<Ingredient> ingredients = ingredientRepository.findAllById(ingredientIds);

        Map<Long, Ingredient> ingredientMap = ingredients.stream()
                .collect(Collectors.toMap(Ingredient::getId, i -> i));

        Map<Ingredient, BigDecimal> result = new LinkedHashMap<>();
        for (RecipeIngredient ri : riList) {
            Ingredient ing = ingredientMap.get(ri.getIngredientId());
            if (ing != null) {
                result.put(ing, ri.getAmount());
            }
        }
        return result;
    }
}
